package com.bobi.tfca.ui.mainnavigation.user.member

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.navigation.findNavController
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentLeaveWordsBinding
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MemberAPI
import com.bobi.tfca.util.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class LeaveWordsFragment : BaseFragment<FragmentLeaveWordsBinding, ViewModel>(
    FragmentLeaveWordsBinding::inflate,
    null,
    true
) {

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentLeaveWordsBinding,
        viewModel: ViewModel?,
        savedInstanceState: Bundle?
    ) {
        // 设置topPanel
        setTopPanelStyle(binding)
        // 得到会员Id
        val memberId = publicViewModel!!.member.value!!.memberId
        // 查询留言
        getMemberById(binding, memberId)
    }

    private fun getMemberById(
        binding: FragmentLeaveWordsBinding,
        memberId: Int
    ) {
        publicViewModel!!.apply {
            request(MemberAPI::class.java).getMemberById(memberId).getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val memberResponse = it.data?.data
                                if (memberResponse != null) {
                                    binding.tvLeaveWords.text = memberResponse.leaveWords
                                    binding.tvMemberName.text = memberResponse.memberName
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentLeaveWordsBinding) {
        val topPanel = binding.topPanel
        topPanel.leftImage.setOnClickListener {
            publicViewModel!!.resetMember()
            requireActivity().findNavController(R.id.app_nav).navigateUp()
        }
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        topPanel.titleText.visibility = View.GONE
    }

}